package client;


import java.io.*;
import java.net.*;

import dictionary.interfaceData.DataListener;
import dictionary.interfaceData.DataReceiver;
import dictionary.interfaceData.NetworkDataWrapper;

/**
 * status:finished, untested
 * @author mjp
 * @version 1.0
 * @created 06-Nov-2011 10:35:00 AM
 */
public class ClientMessager implements DataReceiver {

	private Socket socketWithServer;
	private Client client;

	private ObjectOutputStream out = null;
	private ObjectInputStream in = null;

	public ClientMessager(Client clientIn, String serverIP, int port) 
	{
		attachToServer(serverIP, port);
		this.client = clientIn;
		
		// start listening for Server messages
		new DataListener(this, in).start();
	}
	
	/**
	 * used http://download.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
	 */
	public boolean attachToServer(String serverIP, int port)
	{
		try {
			socketWithServer = new Socket(serverIP, port);
			out = new ObjectOutputStream(socketWithServer.getOutputStream());
            in = new ObjectInputStream(socketWithServer.getInputStream());
		} 
		catch (UnknownHostException e) 
		{
			System.err.println("Don't know about host: "+serverIP+".");
			e.printStackTrace();
            System.exit(1);
		} 
		catch (IOException e) 
		{
			System.err.println("Couldn't get I/O for "
                    + "the connection to: "+serverIP+".");
			e.printStackTrace();
			System.exit(1);
		}
		return true;
	}
	
	public void receiveData(NetworkDataWrapper dataIn)
	{
		client.receiveDataFromServer(dataIn);
	}

	public boolean sendData(NetworkDataWrapper dataIn)
	{
		// sends data to the Server, using the established socket
		try 
		{
			out.writeObject(dataIn);
		} 
		catch (IOException e) 
		{
			System.err.println("Couldn't write message");
			e.printStackTrace();
			System.exit(1);
		}
		return true;
	}
	
}//end ClientMessageLayer